package com.xxq.json;

import java.util.Arrays;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.JavaBeanSerializer;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeWriter;

/**
 * 对JSON类的补充，指定哪些属性输出或不输出
 * */
public class FastJson {
	
	public static String toJson(Object obj) {
		return JSON.toJSONString(obj);
	}

	/**
	 * 只渲染输出对象指定的属性,不支持嵌套属性
	 * */
	public static String toJsonWith(Object obj, String... props) {
		
		SerializeConfig map = new SerializeConfig();
		map.put(obj.getClass(), new JavaBeanSerializer(obj.getClass(), props));
		JSONSerializer serializer = new JSONSerializer(map);
		serializer.write(obj);
        return serializer.toString();
	}
	
	/**
	 * 指定对象的属性不进行渲染输出,不支持嵌套属性
	 * */
	public static String toJsonWithout(Object obj, final String... props) {
		SerializeWriter out = new SerializeWriter();
		try {
			JSONSerializer serializer = new JSONSerializer(out);
			serializer.getPropertyFilters().add(new PropertyFilter() {
				public boolean apply(Object source, String name, Object value) {
					if(Arrays.binarySearch(props, name) >= 0) {
						return false;
					}
					return true;
				}
			});
			serializer.write(obj);
            return out.toString();
        } finally {
            out.close();
        }
	}
	
}
